<template>
  <NModal
    :show="show"
    @update:show="$emit('update:show', $event)"
  >
    <div class="custom-modal included-modal">
      <div class="modal-title">
        <span>关联未入藏藏品</span>
        <img
          src="@/assets/images/meeting_dialog_close.png"
          alt=""
          @click="$emit('update:show', false)"
        />
      </div>
      <div class="modal-container included-container">
        <div class="container-left">
          <div class="select-container">
            <div class="select-list">
              <n-form
                ref="formRef"
                :model="formData1"
                label-placement="left"
                label-width="auto"
                require-mark-placement="right-hanging"
              >
                <n-grid
                  :cols="2"
                  :x-gap="20"
                >
                  <n-grid-item>
                    <n-form-item
                      label="来源"
                      path="key1"
                    >
                      <n-input v-model:value="formData1.key1" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item>
                    <n-form-item
                      label="名称"
                      path="key2"
                    >
                      <n-input v-model:value="formData1.key2" />
                    </n-form-item>
                  </n-grid-item>
                </n-grid>
              </n-form>
            </div>
            <div class="select-btns">
              <n-button
                type="primary"
                @click="handleSelect"
              >
                查询
              </n-button>
              <n-button @click="handleReset">重置</n-button>
            </div>
          </div>
          <div class="table-container">
            <NDataTable
              v-bind="props"
              :bordered="false"
              :row-key="rowKey"
              :columns="columns"
              :data="tableData"
              :loading="tableLoading"
            />
            <NPagination
              :page-sizes="paginationReactive.pageSizes"
              :item-count="paginationReactive.itemCount"
              :page="paginationReactive.page"
              :page-size="paginationReactive.pageSize"
              @update:page="paginationReactive.onChange"
              @update:page-size="paginationReactive.onUpdatePageSize"
              show-size-picker
              show-quick-jumper
              :suffix="() => '页'"
              class="pagination-container"
            >
              <template #prefix>
                <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
              </template>
            </NPagination>
          </div>
        </div>
        <div class="container-right">
          <NScrollbar>
            <DynamicFormComponent
              ref="dfInst"
              v-if="formData.BMCOM003 && !jsonInfoLoading"
              :data="formData"
              :createVars="createVars"
              :onlyTable="isHistory"
              :disabledKeys="['BMCOM008']"
            />
            <!-- <div class="form-card">
              <div class="form-card-title">本地使用块</div>
              <NForm
                ref="formRef1"
                :model="formData1"
                label-placement="left"
                label-width="auto"
                require-mark-placement="right-hanging"
              >
                <n-grid
                  :cols="2"
                  :x-gap="10"
                >
                  <n-grid-item>
                    <n-form-item
                      label="表单项1"
                      path="key1"
                    >
                      <n-input v-model:value="formData1.key1" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item>
                    <n-form-item
                      label="表单项2"
                      path="key2"
                    >
                      <n-input v-model:value="formData1.key2" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item>
                    <n-form-item
                      label="表单项1"
                      path="key1"
                    >
                      <n-input v-model:value="formData1.key3" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item>
                    <n-form-item
                      label="表单项2"
                      path="key2"
                    >
                      <n-input v-model:value="formData1.key4" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item>
                    <n-form-item
                      label="表单项1"
                      path="key1"
                    >
                      <n-input v-model:value="formData1.key5" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item>
                    <n-form-item
                      label="表单项2"
                      path="key2"
                    >
                      <n-input v-model:value="formData1.key6" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item>
                    <n-form-item
                      label="表单项1"
                      path="key1"
                    >
                      <n-input v-model:value="formData1.key7" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item>
                    <n-form-item
                      label="表单项2"
                      path="key2"
                    >
                      <n-input v-model:value="formData1.key8" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item>
                    <n-form-item
                      label="表单项1"
                      path="key1"
                    >
                      <n-input v-model:value="formData1.key9" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item>
                    <n-form-item
                      label="表单项2"
                      path="key2"
                    >
                      <n-input v-model:value="formData1.key10" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item>
                    <n-form-item
                      label="表单项1"
                      path="key1"
                    >
                      <n-input v-model:value="formData1.key11" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item>
                    <n-form-item
                      label="表单项2"
                      path="key2"
                    >
                      <n-input v-model:value="formData1.key12" />
                    </n-form-item>
                  </n-grid-item>
                </n-grid>
              </NForm>
            </div>
            <div class="form-card">
              <div class="form-card-title">标识块</div>
              <NForm
                ref="formRef1"
                :model="formData2"
                label-placement="left"
                label-width="auto"
                require-mark-placement="right-hanging"
              >
                <n-grid
                  :cols="2"
                  :x-gap="10"
                >
                  <n-grid-item>
                    <n-form-item
                      label="表单项1"
                      path="key1"
                    >
                      <n-input v-model:value="formData2.key1" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item>
                    <n-form-item
                      label="表单项1"
                      path="key1"
                    >
                      <n-input v-model:value="formData2.key2" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item>
                    <n-form-item
                      label="表单项1"
                      path="key1"
                    >
                      <n-input v-model:value="formData2.key3" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item>
                    <n-form-item
                      label="表单项1"
                      path="key1"
                    >
                      <n-input v-model:value="formData2.key4" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item>
                    <n-form-item
                      label="表单项1"
                      path="key1"
                    >
                      <n-input v-model:value="formData2.key5" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item>
                    <n-form-item
                      label="表单项1"
                      path="key1"
                    >
                      <n-input v-model:value="formData2.key6" />
                    </n-form-item>
                  </n-grid-item>
                </n-grid>
              </NForm>
            </div> -->
          </NScrollbar>
        </div>
        <div class="container-bottom">
          <div class="btn-list">
            <n-button @click="handleCancel">取消</n-button>
            <n-button
              type="primary"
              @click="handleSubmit"
            >
              确定
            </n-button>
          </div>
        </div>
      </div>
    </div>
  </NModal>
</template>

<script setup lang="ts">
import { ref, reactive, h, watch } from 'vue'
import {
  NForm,
  NFormItem,
  NInput,
  NDataTable,
  NButton,
  NPagination,
  NGrid,
  NGridItem,
  type DataTableColumns,
  NScrollbar,
  NModal
} from 'naive-ui'
import { useViewerStore } from '../../Common/store'
import DynamicFormComponent from '@/components/DynamicFormComponent/index.vue'
import useSubmit, {
  defaultVersionTypeValue,
  defaultVersionTypeKey
} from '@/components/DynamicFormComponent/useSubmit'

const props = defineProps({
  show: {
    type: Boolean,
    required: true
  }
})

const emit = defineEmits(['update:show', 'select', 'reset', 'cancel', 'submit'])

const useStore = useViewerStore()
const { dfInst, formData, createVars, submitLoading, submit: submitR } = useSubmit()

const isHistory = ref(false)

const jsonInfoLoading = ref(false)

// const formData = ref<any>({})
const formData1 = ref<any>({})
const formData2 = ref<any>({})

const formItems = [
  { label: '藏品名称', key: 'key1' },
  { label: '资源码', key: 'key2' },
  { label: '流水号', key: 'key3' },
  { label: '版本类型', key: 'key4' },
  { label: '征集方式', key: 'key5' },
  { label: '藏品状态', key: 'key6' },
  { label: '去向', key: 'key7' },
  { label: '库房位置', key: 'key8' },
  { label: '来源', key: 'key9' },
  { label: '藏品标签', key: 'key10' }
]

const handleSelect = () => {
  emit('select', formData.value)
}

const handleReset = () => {
  formData.value = {}
  emit('reset')
}

const tableLoading = ref(false)
const tableData: any = ref([])
const rowKey: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
  {
    title: 'ISBN',
    key: '1',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '题名',
    key: '2',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '出版者',
    key: '3',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '出版时间',
    key: '4',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '来源',
    key: '5',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '操作',
    key: 'action',
    width: '15rem',
    align: useStore.isCenter,
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {}
        },
        {
          default: () => '关联'
        }
      )
    ]
  }
]
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    // queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    // queryTableData()
  }
})

const handleCancel = () => {
  emit('update:show', false)
  emit('cancel')
}

const handleSubmit = () => {
  emit('update:show', false)
  emit('submit', formData.value)
}

const getInfo = async (subItemCode: any) => {
  sendRequest({
    module: 'collectProcess',
    api: 'catalogInfo',
    uri: {
      subItemCode: subItemCode
    }
  }).then(async ([err, res]) => {
    if (err) return

    // keysOf(res.data.detailVo).forEach((e) => {
    //   form[e] = res.data[e] as never
    // })
    console.log(res)
    GroupList.value = res.data?.itemsStagingList
    if (type.value === '3' || type.value === '1') {
      fileList.value = res.data?.collectingItems?.fileList?.map((e: any, i: number) => ({
        id: i,
        name: e.name,
        status: 'finished',
        url: e.path,
        file: {
          remoteId: e.id
        }
      }))
    }
    form.assetCode = res.data?.itemsStaging?.assetCode
    form.itemName = res.data?.itemsStaging?.itemName
    form.serialNumber = res.data?.itemsStaging?.serialNumber
    form.shelfNumber = res.data?.itemsStaging?.shelfNumber
    // @ts-ignore
    form.choice = (res.data?.collectSetId || '') + ''
    res.data?.collectSetId && makeLineDetail(res.data?.collectSetId)
    isHistory.value = !res.data?.canTaoBian
    // res.data?.detailVo?.itemTypeCode && queryJsonBM(res.data?.detailVo?.itemTypeCode)
    // formData.value = JSON.parse(res.data?.catalogInfo||{})
    getJSONInfo(subItemCode, res.data)
  })
}
const getJSONInfo = async (subItemCode: any, data: any) => {
  jsonInfoLoading.value = true
  return sendRequest({
    module: 'collectProcess',
    api: 'commonJsonInfo',
    uri: {
      subItemCode: subItemCode
    }
  })
    .then(async ([err, res]) => {
      if (err) return
      console.log(res, 'ccc')
      //
      if (res.data?.catalogInfo) {
        formData.value = JSON.parse(res.data?.catalogInfo || '{}')
      }
      //编辑 非空 编目 空的
      if (type.value === '3' && !formData.value[defaultVersionTypeKey]) {
        formData.value[defaultVersionTypeKey] = defaultVersionTypeValue
      }
      // else if(type.value === '2') {
      //   formData.value['BMCOM001']=backDataRef.value?.solicitMethodCode
      // formData.value['BMCOM002']=backDataRef.value?.collector
      // }
      else if (route.query?.type == '1' && !res.data?.catalogInfo) {
        formData.value['BMCOM001'] = backDataRef.value?.solicitMethodCode
        formData.value['BMCOM002'] = backDataRef.value?.collector
        checkIsDetail(route.query?.subItemCode)
      }
      if (isHistory.value) {
        formData.value = {
          ...formData.value,
          ...formatedDataToFormUtil.collectingDistrictDataList(data?.collectingDistrictDataList),
          ...formatedDataToFormUtil.collectingResponsibleDataList(
            data?.collectingResponsibleDataList
          )
        }
        if (formData.value.toString() != '{}')
          formData.value['BMCOM008'] = `${formData.value.ZRZ?.[0]?.['BMLSWX012'] || ''}${
            formData.value.ZRZ?.[0]?.['BMLSWX011']
              ? '(' + formData.value.ZRZ?.[0]?.['BMLSWX011'] + ')'
              : ''
          }${formData.value.ZRZ?.[0]?.['BMLSWX013'] || ''}`
      }

      // ts-ignore
    })
    .finally(() => (jsonInfoLoading.value = false))
}
const checkIsDetail = async (subItemCode: any) => {
  try {
    clueInfoLoading.value = true
    const [error, res] = await sendRequest({
      module: 'collectProcess',
      api: 'commonGoodsInfo',
      uri: {
        subItemCode: subItemCode
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    const { data } = res
    if (!formData.value['BMCOM003']) formData.value['BMCOM003'] = data.itemTypeCode
    if (!formData.value['BMCOM007']) formData.value['BMCOM007'] = data.itemName

    // if(formData.value['BMCOM007']?.indexOf('T01'))
    // {
    //   isHistory.value =true
    //   // getRelativeData()
    // }
    // else
    // {
    //   isHistory.value = false
    // }
  } catch (error) {
    console.error(error)
  } finally {
    setTimeout(() => {
      clueInfoLoading.value = false
    }, 2000)
  }
}
useRouteQuery('id', () => {
  if (route.query.id) {
    // queryJsonBM('T001001')
    if (route.query?.type == '3' || route.query?.type == 1) {
      getInfo(route.query?.subItemCode)
    }

    // queryTableData(true)
  }
})
watch(
  formData,
  (v) => {
    console.log('==>', toRaw(v))
    dfInst.value?.formInst?.$forceUpdate()
  },
  { deep: true }
)
</script>

<style lang="scss" scoped>
.included-modal {
  width: 1376px;
  height: 640px;
  .included-container {
    position: relative;
    padding: 0 0;
    align-items: flex-start;
    display: flex;
    overflow: hidden;
  }
  .container-left {
    flex: 1;
    height: 100%;
    padding: 24px;
    position: relative;
    .select-container {
      display: flex;
      align-items: center;
      gap: 19px;
      .select-line,
      .select-btns {
        margin-top: -20px;
      }
      .select-line {
        width: 84px;
        height: 1px;
        transform: rotate(90deg);
        background: #f1f2f4;
      }
      .select-btns {
        display: flex;
        gap: 20px;
      }
    }
    .pagination-container {
      position: absolute;
      bottom: 80px;
    }
  }
  .container-right {
    flex: 1;
    height: calc(100% - 80px);
    padding: 20px 23px 0 0;
    position: relative;
    overflow: hidden;
    .form-card {
      width: 100%;
      margin-bottom: 20px;
      padding: 16px 24px 0;
      border-radius: 4px;
      border: 1px solid #c9cdd4;
      background: #f7f8f9;
      &-title {
        margin-bottom: 16px;
        color: #2d3339;
        font-size: 14px;
        font-weight: 600;
        line-height: 24px; /* 171.429% */
      }
    }
  }
  .container-bottom {
    position: absolute;
    bottom: 0;
    display: flex;
    width: 100%;
    height: 56px;
    padding: 0px 24px;
    justify-content: center;
    align-items: center;
    gap: 24px;
    border-top: 1px solid #e2e2e2;
    .btn-list {
      display: flex;
      gap: 24px;
    }
  }
}
:deep(.n-form-item-feedback-wrapper) {
  min-height: 20px;
}
:deep(.n-form-item-label__text) {
  color: #4e5969;
  text-align: right;
  font-size: 12px;
  line-height: 22px; /* 183.333% */
}
:deep(.n-form-item-blank) {
  width: 168px;
}
</style>
